package io.codegeneratetool.impl.entity.dbutil;

import io.codegeneratetool.core.CodeGenerateOptions;
import io.codegeneratetool.vo.db.DB_Column;
import io.codegeneratetool.vo.db.DB_Table;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MysqlTableInfoGetter extends TableInfoGetter {
 
	private static final String searchAllTablesql="select t.table_name,c.comments  from user_tables t,user_tab_comments c  where t.table_name=c.table_name ";
 
	@Override
	public List<DB_Table> getTables(CodeGenerateOptions codeGenerateOptions){
		 
		List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(searchAllTablesql);
		List<DB_Table> db_Tables = new ArrayList<DB_Table>();
		DB_Table table = null ;
		for (Map<String, Object> map : queryForList) {
			table = new DB_Table();
			table.setName(map.get("TABLE_NAME").toString());
			Object object = map.get("COMMENTS");
			table.setComment(object==null?"":object.toString());
			db_Tables.add(table); 
		}
		return db_Tables;
	}
	

 	@Override
	public DB_Table getTable(CodeGenerateOptions codeGenerateOptions,String tableName){
 		 
		Map<String, Object> map = jdbcTemplate.queryForMap(searchAllTablesql+ " and t.table_name=?", tableName);
		 
		DB_Table table =   new DB_Table();
		table.setName(map.get("TABLE_NAME").toString());
		Object object = map.get("COMMENTS");
		table.setComment(object==null?"":object.toString()); 
		return table;
	}
 	
  
	@Override
	public List<DB_Column> getColumns(CodeGenerateOptions codeGenerateOptions,String tableName){
		final String sql = "select COL.COLUMN_NAME name,COL.DATA_TYPE type,COL.DATA_LENGTH length , COL.DATA_TYPE type ,C.COMMENTS comments  from user_tab_columns col  , user_col_comments c "+
				"where COL.TABLE_NAME = C.TABLE_NAME and COL.COLUMN_NAME = C.COLUMN_NAME  and COL.TABLE_NAME=?";
		 
		List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql, tableName);
		List<DB_Column> columns = new ArrayList<DB_Column>();
		DB_Column column = null ;
		for (Map<String, Object> map : queryForList) {
			column = new DB_Column();
			column.setName(map.get("NAME").toString());
			Object object = map.get("COMMENTS");
			column.setComment(object==null?"":object.toString());
			column.setType(map.get("TYPE").toString());
			
			column.setLength(Integer.parseInt(map.get("LENGTH").toString()));
			
			
			columns.add(column); 
		}
		return columns; 
	}


	@Override
	public List<String> getAllTables() {
		List<String> queryForList = jdbcTemplate.queryForList("show tables",String.class);
		 
		return queryForList;
	}
	
}
